package com.sky.service.impl;

import ch.qos.logback.core.joran.util.beans.BeanUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.OrderService;
import com.sky.utils.BaidulLocationUtil;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {

    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;


    @Override
    @Transactional
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {

        AddressBook addressBook = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
//判断地址是否为空
        if (addressBook == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //异常情况的处理（超出配送范围）TODO 超出配送范围
        String address = "";
        //拼装用户地址
        address = address + addressBook.getProvinceName() + addressBook.getDistrictName() + addressBook.getDetail();


        String userLatAndLng = BaidulLocationUtil.getLatAndLng(address);
        String shopLatAndLng = BaidulLocationUtil.getLatAndLng("上海市浦东新区奋斗者之家");

        String flag = BaidulLocationUtil.getGap(userLatAndLng, shopLatAndLng).get("error");

        //flag不为null，说明调用百度路线规划接口发生异常
        if (flag != null) {
            throw new AddressBookBusinessException(flag);
        }
        //配送距离超出5公里则不允许下单
        String s = BaidulLocationUtil.getGap(userLatAndLng, shopLatAndLng).get("distance");
        if (Integer.parseInt(s) > 5000) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_FAR);
        }


//        获取当前用户id
        Long userId = BaseContext.getCurrentId();
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
//查询当前用户购物车数据
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.list(shoppingCart);
//     判断购物车是否为空
        if (shoppingCartList == null || shoppingCartList.size() < 1) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        Orders order = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, order);
        order.setPhone(addressBook.getPhone());
        order.setAddress(addressBook.getDetail());
        order.setConsignee(addressBook.getConsignee());
        order.setNumber(String.valueOf(System.currentTimeMillis()));
        order.setUserId(userId);
        order.setStatus(Orders.PENDING_PAYMENT);
        order.setPayStatus(Orders.UN_PAID);
        order.setOrderTime(LocalDateTime.now());
//        向订单插入1条数据
        orderMapper.insert(order);
//        订单明细数据
        List<OrderDetail> orderDetailList = new ArrayList<>();
//      遍历购物车里的物品，然后塞进订单
        for (ShoppingCart cart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(cart, orderDetail);
            orderDetail.setOrderId(order.getId());
            orderDetailList.add(orderDetail);

        }
        //向订单插入多条数据
        orderDetailMapper.insertBatch(orderDetailList);
        //  清空购物车数据
        shoppingCartMapper.cleanShoppingCartByUserId(userId);
        //分装返回结果
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(order.getId())
                .orderNumber(order.getNumber())
                .orderAmount(order.getAmount())
                .orderTime(order.getOrderTime())
                .build();


        return orderSubmitVO;
    }

    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     * @throws Exception
     */
    @Override
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
//当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);
//调用微信支付接口，生成预支付交易单

        JSONObject jsonObject = weChatPayUtil.pay(ordersPaymentDTO.getOrderNumber(),
                new BigDecimal(0.01),//支付金额
                "苍穹外卖订单",//商品描述
                user.getOpenid());//微信用户的openid

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }
        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));
        return vo;
    }

    @Override
    public void paySuccess(String outTradeNo) {
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo);
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();
        orderMapper.update(orders);

    }

    /**
     *c- 根据id查看订单详情
     *
     * @param id
     * @return
     */
    @Override
    public OrderVO selectById(Long id) {
        OrderVO orderVO = orderMapper.getOrderById(id);
        List<OrderDetail> orderDetails = orderDetailMapper.getOrderDetailById(orderVO.getId());
        StringBuilder orderDishes = new StringBuilder();
        for (OrderDetail orderDetail : orderDetails) {
            orderDishes.append(orderDetail.getName()).append("*").append(orderDetail.getNumber()).append(",");

        }
        orderVO.setOrderDishes(orderDishes.toString());
        orderVO.setOrderDetailList(orderDetails);
        return orderVO;
    }

    /**
     * C-取消订单
     *
     * @param id
     */
    @Override
    public void cancelOrder(Long id) {
        //根据id获取订单详情
        Orders orderId = orderMapper.getByOrderId(id);
//       校验订单是否存在
        if (orderId == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
//        订单状态  1：待付款  2：待接单  3：已接单   4：派送中   5：已完成  6：已取消
        if (orderId.getStatus() > 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);

        }
        Orders orders = new Orders();
        orders.setId(orderId.getId());
//    订单处于待接单状态下取消，需要退款
        if (orderId.getStatus().equals(Orders.TO_BE_CONFIRMED)) {
            orders.setPayStatus(Orders.REFUND);//退款
        }
//更新订单状态，取消原因、时间
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason("用户取消");
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);
    }


    @Override
    public PageResult historyOrdersPage(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());

        //查询订单信息
        List<OrderVO> historyOrdersList = orderMapper.historyOrdersPage(ordersPageQueryDTO);

        //查询订单详情信息
        for (OrderVO orderVO : historyOrdersList) {
            List<OrderDetail> orderDetails = orderDetailMapper.getOrderDetailById(orderVO.getId());

            //设置订单菜品信息
            StringBuilder orderDishes = new StringBuilder();
            for (OrderDetail orderDetail : orderDetails) {
                orderDishes.append(orderDetail.getName()).append("*").append(orderDetail.getNumber()).append(";");
            }
            orderVO.setOrderDishes(orderDishes.toString());
            orderVO.setOrderDetailList(orderDetails);
        }

        Page<OrderVO> page = (Page<OrderVO>) historyOrdersList;

        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 再来一单
     *
     * @param id
     */
    @Override
    public void repetition(Long id) {
//        创建购物车对象
        Orders orders = orderMapper.getByOrderId(id);
//        根据id找出购物车里对应的商品
        List<OrderDetail> orderDetailList = orderDetailMapper.getOrderDetailById(orders.getId());
        for (OrderDetail orderDetail : orderDetailList) {
            ShoppingCart shoppingCart = new ShoppingCart();

//            重新把商品塞入购物车
            BeanUtils.copyProperties(orderDetail, shoppingCart);
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartMapper.insert(shoppingCart);

        }


    }

    /**
     * 管理端--订单分页查询
     *
     * @param ordersPageQueryDTO
     * @return
     */
    @Override
    public PageResult adminPage(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        List<OrderVO> orderVOList = orderMapper.historyOrdersPage(ordersPageQueryDTO);
        for (OrderVO orderVO : orderVOList) {
            List<OrderDetail> orderDetailById = orderDetailMapper.getOrderDetailById(orderVO.getId());
            StringBuilder orderDishes = new StringBuilder();
            for (OrderDetail orderDetail : orderDetailById) {
                orderDishes.append(orderDetail.getName()).append("*").append(orderDetail.getNumber()).append(",");

            }
            orderVO.setOrderDishes(orderDishes.toString());
            orderVO.setOrderDetailList(orderDetailById);
        }
        Page<OrderVO> page = (Page<OrderVO>) orderVOList;
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 各个状态的订单数量统计
     *
     * @return
     */
    @Override
    public OrderStatisticsVO statistics() {
        OrderStatisticsVO orderStatisticsVO = new OrderStatisticsVO();
        orderStatisticsVO.setConfirmed(orderMapper.selectCount(3));
        orderStatisticsVO.setDeliveryInProgress(orderMapper.selectCount(4));
        orderStatisticsVO.setToBeConfirmed(orderMapper.selectCount(2));
        return orderStatisticsVO;
    }

    /**
     * 接单
     *
     * @param ordersConfirmDTO
     */
    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
//        根据id查询订单，判断当前订单状态
        Orders orderId = orderMapper.getByOrderId(ordersConfirmDTO.getId());
        //判断该订单是否是待接单状态
        if (orderId.getStatus() != 2) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);
        }
        Orders orders = new Orders();
        orders.setId(ordersConfirmDTO.getId());
        orders.setStatus(Orders.CONFIRMED);//已接单
        orderMapper.update(orders);

    }

    /**
     * 拒单
     *
     * @param ordersRejectionDTO
     */
    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        //修改订单状态，支付状态等
        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersRejectionDTO,orders);
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelTime(LocalDateTime.now());
        orders.setCancelReason(ordersRejectionDTO.getRejectionReason());//设置取消原因为拒绝原因
        orderMapper.update(orders);
    }

    @Override
    public void adminCancelOrder(OrdersCancelDTO ordersCancelDTO) {
//查看当前订单状态，如果已完成则不能取消
        Orders orderId = orderMapper.getByOrderId(ordersCancelDTO.getId());
        if (orderId.getStatus() == 5) {
            throw new OrderBusinessException(MessageConstant.ORDER_STATUS_ERROR);

        }
        //修改订单信息
        Orders orders = new Orders();
        orders.setStatus(Orders.CANCELLED);
        orders.setId(ordersCancelDTO.getId());
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orders.setCancelTime(LocalDateTime.now());
        orderMapper.update(orders);


    }

    /**
     * 派单
     *
     * @param id
     */
    @Override
    public void delivery(Long id) {
        //根据id查询订单，判断订单是否存在
        Orders orders = orderMapper.getByOrderId(id);
        if (orders == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);

        orderMapper.update(orders);
    }

    /**
     * 完成订单
     *
     * @param id
     */
    @Override
    public void complete(Long id) {
        //根据id查询订单，判断订单是否存在
        Orders orderId = orderMapper.getByOrderId(id);
        if (orderId == null) {
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        Orders orders = new Orders();
        orders.setId(id);
        orders.setStatus(Orders.COMPLETED);
        orders.setDeliveryTime(LocalDateTime.now());
        orderMapper.update(orders);

    }
}
